package com.MusicWeb.servlet;

import com.MusicWeb.entity.Music;
import com.MusicWeb.service.UsermusicService;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/music")
public class MusicServlet extends HttpServlet {
    UsermusicService usermusicService = new UsermusicService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        //从网页获取用户的信息
        String music_name = req.getParameter("music_name");
        String music_singer = req.getParameter("music_singer");
        String music_text = req.getParameter("music_text");
        String music_url = req.getParameter("music_url");
        //装入实体
        Music music = new Music();
        music.setMusic_name(music_name);
        music.setMusic_singer(music_singer);
        music.setMusic_text(music_text);
        music.setMusic_url(music_url);
        if (usermusicService.instermusic(music) != null) {
            // 设置返回的数据为json对象
            resp.setContentType("application/json;charset=utf-8");
            // 把实体转换为json，返回给前端
            String str = new Gson().toJson(music);
            resp.getWriter().print(str);
            //返回提交的音乐信息
            req.getSession().setAttribute("msg", "提交成功");
        } else {
            req.getSession().setAttribute("msg", "提交失败");
        }
    }
}
